package uts.sdk.utsEncrypt

import org.apache.commons.codec.binary.Base64
import java.security.*
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import javax.crypto.Cipher

class RasTool {
    companion object {

        @Throws(Exception::class)
        @JvmStatic
        fun encryptByPrivateKey(privateKeyString: String?, text: String): String? {
            val pkcs8EncodedKeySpec = PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString))
            val keyFactory = KeyFactory.getInstance("RSA")
            val privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec)
            val cipher = Cipher.getInstance("RSA")
            cipher.init(Cipher.ENCRYPT_MODE, privateKey)
            val result = cipher.doFinal(text.toByteArray())
            return Base64.encodeBase64String(result)
        }

        @Throws(Exception::class)
        @JvmStatic
        fun decryptByPublicKey(publicKeyString: String?, text: String): String {
            val x509EncodedKeySpec: X509EncodedKeySpec = X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
            val keyFactory: KeyFactory = KeyFactory.getInstance("RSA");
            val publicKey: PublicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            val cipher: Cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            val result: ByteArray = cipher.doFinal(Base64.decodeBase64(text));
            return result.toString();
        }
    }
}